package 线程安全问题.关于synchronized.银行账户模拟.Test02;

//不使用线程同步机制,多线程对同一个账户进行取款，出现线程安全问题
public class Account {
    private String actno;
    private double balance;

    public Account(String actno, double balance) {
        this.actno = actno;
        this.balance = balance;
    }

    public Account() {
    }

    public String getActno() {
        return actno;
    }

    public void setActno(String actno) {
        this.actno = actno;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    public void withdraw(double money){
        synchronized (this){//小括号里还能写"abc"字符串还有很多只要是一个实例变量,但这样所有的线程都会同步
            double before = this.getBalance();
            double after = before - money;
            //模拟网络延迟
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            this.setBalance(after);
        }
    }
}







































